import {
  formatTime,
  formatHour
} from '../../utils/util.js'

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    courseId: '',
    videoUrl: '',
    detail: {},
    showVideo: false,
    isShowTest: false,
    videoId: 0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      courseId: options.courseId
    })
  },
  onShow() {
    this.queryCourse();
  },
  // 获取课程测试题目
  getTest() {
    app.fetchRequest({
      url: `/user/exam/start/${this.data.detail.id}`,
      data: {},
      success: (res) => {
        if (res.length) {
          if (!this.data.isShowTest) return;
          this.setData({
            isShowTest: true
          })
        } else {
          this.setData({
            isShowTest: false
          })
        }
      }
    })
  },
  // 查询课程
  queryCourse() {
    app.fetchRequest({
      url: '/course/query',
      data: {
        courseSeq: this.data.courseId
      },
      success: (res) => {
        if (res && res.list && res.list.length) {
          res.list.forEach(item => {
            item.createTime = formatTime(new Date(item.createTime));
            item.updateTime = formatTime(new Date(item.updateTime));
            item.totalDuration = formatHour(item.totalDuration);
            if (item.videos.length) {
              item.videos.forEach(vItem => {
                vItem.videoTime = formatHour(vItem.duration);
              })
              const allWatched = item.videos.some(vItem => !vItem.watched)
              this.setData({
                isShowTest: !allWatched
              })
            }
          })
          this.setData({
            detail: res.list[0]
          })
          this.getTest();
        }

      }
    })
  },
  // 收藏
  collect() {
    app.fetchRequest({
      url: `/user/exam/collect/${this.data.detail.id}`,
      data: {},
      success: (res) => {
        this.data.detail.collectMark = !this.data.detail.collectMark;
        this.setData({
          detail: this.data.detail
        })
        //this.queryCourse();
      }
    })
  },
  watch(e) {
    const index = e.currentTarget.dataset.index;
    const url = this.data.detail.videos[index].videoLink;
    const videoId = this.data.detail.videos[index].id;
    const duration = this.data.detail.videos[index].duration;
    wx.navigateTo({
      url: `../video/video?url=${url}&videoId=${videoId}&duration=${duration}`,
    })
  },
  toCourseScript() {
    if (this.data.detail.note) {
      wx.navigateTo({
        url: `../course-script/course-script?courseId=${this.options.courseId}`,
      })
    }
  },
  courseTest() {
    wx.navigateTo({
      url: `../course-test/course-test?courseId=${this.data.detail.id}&courseName=${this.data.detail.courseName}&status=${this.data.detail.passMark}`,
    })
  }

})